<route lang="json5">
{
  style: {
    navigationBarTitleText: '报告详情',
    navigationBarBackgroundColor: '#FFFFFF',
  },
}
</route>

<template>
  <view class="view-report">
    <web-view :src="url"></web-view>
  </view>
</template>

<script lang="js" setup>
import { showModal } from '@/utils/publicMethods'
import { getPdf } from '@/service/index/default'
const url = ref('')

onLoad(async (option) => {
  if (!option?.id) {
    await showModal({ title: '查询参数id异常' })
    return uni.navigateBack()
  }
  url.value = getPdf(option.id)
  // -------------------微信分享----------------------
  // 分享至好友/群聊
  onShareAppMessage((res) => {
    return {
      title: '报告详情',
      path: `/pages-sub/reportDetail/index?id=${option.id}`,
      success: (res) => {},
      fail: (res) => {},
    }
  })
  // 分享到朋友圈
  onShareTimeline((res) => {
    return {
      title: '报告详情',
      path: `/pages-sub/reportDetail/index?id=${option.id}`,
      success: (res) => {},
      fail: (res) => {},
    }
  })
})

/* ------------------------------弃用版-------------------------------- */
const getPDF = (binaryData) => {
  const filePath = wx.env.USER_DATA_PATH + '/诊断结论.pdf'
  wx.getFileSystemManager().writeFile({
    filePath: filePath,
    data: binaryData,
    encoding: 'binary',
    success(res) {
      // 在写入文件后，验证文件是否存在
      wx.getFileSystemManager().readFile({
        filePath: filePath,
        encoding: 'binary',
        success(readRes) {
          console.log('文件读取成功', readRes)

          wx.openDocument({
            filePath: filePath,
            success(res) {
              console.log('打开成功')
            },
            fail(err) {
              console.log('打开失败', err)
            },
          })
        },
        fail(err) {
          console.log('文件读取失败', err)
        },
      })
    },
    fail(err) {
      console.log('文件写入失败', err)
    },
  })
}

//通过base64打开pdf文件
function openPdfFromBase64(base64Data) {
  return new Promise((resolve, reject) => {
    // 处理 base64Data，去除换行符
    let result = base64Data.replace(/[\r\n]/g, '')
    let pdfBase64 = `data:application/pdf;base64,${result}`

    // 将 base64 转换为文件路径
    base64ToPath(pdfBase64)
      .then((path) => {
        // 使用 uni.openDocument 打开文档
        uni.openDocument({
          filePath: path,
          success: function (FileRes) {
            console.log('打开成功')
            resolve('打开成功') // 成功后返回
          },
          fail: (res) => {
            console.log('打开失败')
            reject('打开失败') // 失败时返回
          },
        })
      })
      .catch((error) => {
        console.error(error)
        reject(error) // 转换 base64 为路径失败时返回错误
      })
  })
}
</script>

<style lang="scss" scoped></style>
